package com.sina.shop.config;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sina.shop.util.JsonUtils;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

/**
 * 专用于 json 视图配置
 * created  on 04/07/2017.
 */
@Configuration
public class JsonViewConfig {

    @Bean
    public ObjectMapper jsonViewObjectMapper(@Qualifier("shopSessionFactory") SessionFactory sessionFactory){
        return JsonUtils.createDefaultObjectMapper(sessionFactory);
    }

    /*@Bean("commonView")
    public View commonView(@Qualifier("jsonViewObjectMapper") ObjectMapper objectMapper){
        MappingJackson2JsonView view = new MappingJackson2JsonView(objectMapper);
        view.setModelKey("common");
        view.setExtractValueFromSingleKeyModel(true);
        view.setContentType( MediaType.APPLICATION_JSON_UTF8_VALUE );
        return view;
    }*/

    @Bean
    public static MappingJackson2JsonView commonView(@Qualifier("jsonViewObjectMapper")
                                                             ObjectMapper objectMapper) {
        MappingJackson2JsonView view = new MappingJackson2JsonView(objectMapper);
        view.setExtractValueFromSingleKeyModel(true);
        view.setModelKey("result");
        view.setEncoding(JsonEncoding.UTF8);
        return view;
    }

}
